// pages/location/index.js
Page({
  data: {
    latitude: "",
    longitude: "",
    searchValue: "",
    districtList: [],
    select_index: "-1",
    page_index: 1,
    isNoMore: true,
    isLoding: true
  },
  onLoad: function (options) {},
  onShow: function () {
    // 获取用户授权信息
    wx.getSetting({
      success: (res) => {
        console.log("授权信息", res.authSetting)
        if (!res.authSetting["scope.userLocation"] && res.authSetting["scope.userLocation"] != undefined) {
          getApp().globalData.vant.dialog.confirm({
            title: "温馨提示",
            message: "位置授权是为了给您定位居住小区，确保小区及人员信息的真实安全~",
            showCancelButton: false,
            confirmButtonText: "授权登录",
            confirmButtonOpenType: "openSetting",
            confirmButtonColor: "#33B868"
          }).then(() => {});
        } else {
          wx.getLocation({
            type: "gcj02",
            success: (data) => {
              this.setData({
                latitude: data.latitude,
                longitude: data.longitude
              });
              this.getData();
            },
            fail: () => {}
          });
        }
      },
      fail: () => {}
    });
  },
  getData() {
    getApp().globalData.http.getCommunity({
      keyword: !this.data.searchValue ? "小区" : this.data.searchValue,
      boundary: `nearby(${this.data.latitude},${this.data.longitude},1000,1)`,
      filter: "category=住宅区,住宅小区,其它住宅区",
      orderby: "_distance",
      page_index: this.data.page_index,
      page_size: 20
    }).then(res => {
      let data_tmp = [...this.data.districtList, ...res.data];
      this.setData({
        districtList: data_tmp,
        isLoding: true
      });
      if (this.data.districtList.length == res.count) {
        this.setData({
          isNoMore: false
        });
      }
    });
  },
  searchHandle() {
    this.setData({
      districtList: [],
      select_index: -1,
      page_index: 1,
      isNoMore: true,
      isLoding: true
    });
    this.getData();
  },
  select(e) {
    this.setData({
      select_index: e.currentTarget.dataset.index
    });
    getApp().globalData.http.saveCommunity({
      data: JSON.stringify(this.data.districtList[this.data.select_index])
    }).then(res => {
      getApp().globalData.vant.toast({
        type: "success",
        duration: 1000,
        message: "操作成功",
        onClose: () => {
          wx.setStorageSync("set_community", this.data.districtList[this.data.select_index])
          wx.navigateBack({
            success: function (e) {
              let page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
              page.getUserCommunity();
            }
          });
        },
      });
    });
  },
  onReachBottom() {
    if (this.data.isNoMore) {
      this.setData({
        page_index: this.data.page_index / 1 + 1,
        isLoding: false
      });
      this.getData();
    }
  },
})